package com.jdrx.sw.sewage.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.jdrx.ocp.service.UserService;
import com.jdrx.platform.commons.rest.beans.vo.ResponseVO;
import com.jdrx.platform.commons.rest.factory.ResponseFactory2;
import com.jdrx.sw.sewage.beans.dto.DevStorageDTO;
import com.jdrx.sw.sewage.beans.entity.CategoryPO;
import com.jdrx.sw.sewage.beans.entity.DevStoragePO;
import com.jdrx.sw.sewage.beans.entity.DeviceStorageRecordPO;
import com.jdrx.sw.sewage.beans.entity.FactoryPO;
import com.jdrx.sw.sewage.beans.vo.*;
import com.jdrx.sw.sewage.common.constant.Constant;
import com.jdrx.sw.sewage.common.enums.StorageDevType;
import com.jdrx.sw.sewage.common.util.SpringBeanUtil;
import com.jdrx.sw.sewage.dao.*;
import com.jdrx.sw.sewage.service.common.SequenceDefineServiceImpl;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Objects;

import static com.jdrx.sw.sewage.common.constant.Constant.DEVICE_STORAGE;
import static com.jdrx.sw.sewage.common.constant.Constant.TRANSPARENT_USERNAME_FEILD;

@Service
public class DevStorageImportServiceImpl extends AnalysisEventListener<ExcelDevStorageVO> {

    public static final Logger logger = LoggerFactory.getLogger(DevStorageImportServiceImpl.class);
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CategoryDAO categoryDAO;
    @Autowired
    private FactoryDAO factoryDAO;
    @Autowired
    private MaterielDAO materielDAO;
    @Autowired
    private DevStorageTypeDAO devStorageTypeDAO;
    @Autowired
    private SequenceDefineServiceImpl sequenceDefineServiceImpl;
    @Autowired
    private DevStorageServiceImpl devStorageServiceImpl;
    @Autowired
    private DevStorageRecordDAO devStorageRecordDAO;
    @Autowired
    private UserService userService;

    /**
     * 这个每一条数据解析都会来调用
     */
    @SneakyThrows
    @Override
    public void invoke(ExcelDevStorageVO data, AnalysisContext context) {
        logger.info("解析到一条数据:{}", JSON.toJSONString(data));
        String materielName = data.getMaterielName();
        String categoryName = data.getCategoryName();
        String factoryName = data.getFactoryName();
        CategoryVO devStorageVO = categoryDAO.selectByName(categoryName);
        MaterielVO materielVO = materielDAO.selectByName(materielName);
        String userName = URLDecoder.decode(request.getHeader(TRANSPARENT_USERNAME_FEILD), "UTF-8");
        if (Objects.isNull(devStorageVO)) {
            CategoryPO categoryPO = new CategoryPO();
            categoryPO.setMaterielId(materielVO.getId());
            categoryPO.setName(categoryName);
            categoryDAO.insert(categoryPO);
            devStorageVO = new CategoryVO();
            devStorageVO.setId(categoryDAO.selectNextId() - 1);
        }
        FactoryVO factoryVO = factoryDAO.selectByName(factoryName);
        if (Objects.isNull(factoryVO)) {
            FactoryPO factoryPO = new FactoryPO();
            factoryPO.setName(factoryName);
            factoryDAO.insert(factoryPO);
            factoryVO = new FactoryVO();
            factoryVO.setId(factoryDAO.selectNextId() - 1);
        }

        DevStorageDTO devStorageDTO = new DevStorageDTO();
        devStorageDTO.setMaterielId(materielVO.getId());
        devStorageDTO.setCategoryId(devStorageVO.getId());
        devStorageDTO.setDossierSpec(data.getDossierSpec());
        devStorageDTO.setPurchaseTime(data.getPurchaseTime());
        devStorageDTO.setCreateAt(new Date());
        DevStorageTypeVO devStorageTypeVO = devStorageTypeDAO.findDevStorTypeByMatIdAndCatIdAndDossierSpec(devStorageDTO);
        if (Objects.isNull(devStorageTypeVO)) {
            devStorageDTO.setFactoryIds("," + factoryVO.getId() + ",");
            devStorageDTO.setPlcLogicPoint(0);
            devStorageTypeDAO.add(devStorageDTO);
            devStorageTypeVO = new DevStorageTypeVO();
            devStorageTypeVO.setId(devStorageTypeDAO.selectNextId() - 1);
        } else {
//            String factoryIds = devStorageTypeVO.getFactoryIds() + "," + factoryVO.getId();
            String orderFactoryIds = devStorageTypeVO.getFactoryIds();
            String addFactoryId = factoryVO.getId() + ",";
            String factoryIds = null;
            if (!orderFactoryIds.contains("," + addFactoryId))
                factoryIds = orderFactoryIds + addFactoryId;
            else factoryIds = orderFactoryIds;

            devStorageTypeDAO.update(devStorageDTO.getAttach(), devStorageTypeVO.getId(), factoryIds);
        }

        DevStoragePO devStoragePO = new DevStoragePO();
        BeanUtils.copyProperties(devStorageDTO, devStoragePO);
        devStoragePO.setStorageTypeId(devStorageTypeVO.getId());
        devStoragePO.setFactoryId(factoryVO.getId());
        devStoragePO.setMaintenanceCycleDay(data.getMaintenanceCycleDay());
        devStoragePO.setMaintenanceCycleHour(data.getMaintenanceCycleHour());
        devStoragePO.setCreateAt(new Date());
        devStoragePO.setDevType(StorageDevType.ATTACHMENT.getKey());
        devStoragePO.setSnNum(data.getSnNum());
        devStoragePO.setCycleTime(data.getMaintenanceCycleDay());
        devStoragePO.setWorkTime(data.getMaintenanceCycleHour());
        devStoragePO.setPlcLogicPoint(0);
        devStoragePO.setInitWorkTime(0);
        devStoragePO.setCreateBy(userName);
        for (int i = 0; i < data.getStorageNum(); i++) {
            devStoragePO.setDeviceNum(String.format("JD%08d", sequenceDefineServiceImpl.increment(Constant.SEQ_SN_KEY, null)));
            devStorageServiceImpl.add(devStoragePO);
        }

        DeviceStorageRecordPO storageRecordPO = new DeviceStorageRecordPO();
        storageRecordPO.setCreateAt(new Date());
        storageRecordPO.setCreateBy(userName);
        storageRecordPO.setStorageTypeId(devStorageTypeVO.getId());
        storageRecordPO.setRecordInfo(String.format(DEVICE_STORAGE, data.getStorageNum()));
        devStorageRecordDAO.add(storageRecordPO);
    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        logger.info("所有数据导入完成！");
    }

    public ResponseVO deviceStorageImport(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), ExcelDevStorageVO.class, SpringBeanUtil.getBean(DevStorageImportServiceImpl.class))
                .sheet()
                .doRead();
        return ResponseFactory2.ok("导入成功");
    }
}